package com.getpebble.android.framework.firmware;

import android.content.ContentProviderOperation;
import android.content.ContentValues;
import android.content.Context;
import android.content.OperationApplicationException;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.database.sqlite.SQLiteException;
import android.os.RemoteException;
import com.getpebble.android.common.core.async.PblAsyncTask;
import com.getpebble.android.common.core.trace.Trace;
import com.getpebble.android.common.core.util.PblContentProviderUtil;
import com.getpebble.android.common.core.util.PblPreferences;
import com.getpebble.android.common.core.util.PblPreferences.PrefKey;
import com.getpebble.android.common.model.FirmwareVersion;
import com.getpebble.android.common.model.HardwarePlatform;
import com.getpebble.android.common.model.PblDevice;
import com.getpebble.android.common.model.PblDeviceModel;
import com.getpebble.android.common.model.PblFirmwareManifestModel;
import com.getpebble.android.framework.firmware.FirmwareManifestBundle.ReleaseType;
import com.getpebble.android.framework.install.firmware.FirmwareBundleManager;
import com.google.common.primitives.UnsignedInteger;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class FirmwareManifestSync {
    public static final String TAG = FirmwareManifestSync.class.getSimpleName();
    private static final Object sSyncLock = new Object();
    private Context mContext;

    public FirmwareManifestSync(Context context) {
        this.mContext = context;
    }

    private Context getContext() {
        return this.mContext;
    }

    public void syncForAllConnectedDevices() {
        synchronized (sSyncLock) {
            doSyncForAllConnectedDevices();
        }
    }

    private void doSyncForAllConnectedDevices() {
        Trace.debug(TAG, "Syncing firmware manifest");
        final ReleaseType releaseType = getUpdateChannel();
        if (releaseType.equals(ReleaseType.UNKNOWN)) {
            Trace.error(TAG, "Unknown release type: Cannot sync firmware manifests.");
        } else {
            new PblAsyncTask() {
                public boolean doInBackground() {
                    List<FirmwareManifestBundle> existingBundles = FirmwareManifestSync.this.fetchCurrentManifests();
                    List<FirmwareManifestBundle> bundlesToAdd = new ArrayList();
                    List<FirmwareManifestBundle> bundlesToDelete = new ArrayList();
                    Map<HardwarePlatform, FirmwareVersion> platformVersionData = FirmwareManifestSync.this.fetchPlatformVersionData();
                    if (platformVersionData.isEmpty()) {
                        Trace.info(FirmwareManifestSync.TAG, "No devices found.  No firmware will be synced.");
                        return false;
                    }
                    for (HardwarePlatform hardwarePlatform : platformVersionData.keySet()) {
                        Trace.debug(FirmwareManifestSync.TAG, "About to sync for: " + hardwarePlatform.getName());
                        FirmwareManifestBundle bundle = FirmwareManifestSync.this.fetchBundle(hardwarePlatform, releaseType);
                        if (bundle != null) {
                            FirmwareManifestBundle existingBundle = FirmwareManifestSync.findMatchingBundle(hardwarePlatform, releaseType, existingBundles);
                            FirmwareVersion bundleFirmwareVersion = bundle.getNormalMetadata().getFriendlyVersion();
                            FirmwareVersion oldestRunningFirmwareVersion = (FirmwareVersion) platformVersionData.get(hardwarePlatform);
                            Trace.debug(FirmwareManifestSync.TAG, "Bundle Firmware Version: " + bundleFirmwareVersion + ", Timestamp: " + bundleFirmwareVersion.getTimestamp());
                            Trace.debug(FirmwareManifestSync.TAG, "Oldest Firmware Version: " + oldestRunningFirmwareVersion + ", Timestamp: " + oldestRunningFirmwareVersion.getTimestamp());
                            if (bundleFirmwareVersion.compareTo(oldestRunningFirmwareVersion) <= 0) {
                                Trace.debug(FirmwareManifestSync.TAG, "Firmware is up-to-date.");
                                if (existingBundle != null) {
                                    Trace.debug(FirmwareManifestSync.TAG, "Already installed bundle will be deleted.");
                                    bundlesToDelete.add(existingBundle);
                                }
                            } else if (existingBundle == null || bundleFirmwareVersion.compareTo(existingBundle.getNormalMetadata().getFriendlyVersion()) != 0) {
                                Trace.debug(FirmwareManifestSync.TAG, "New bundle will be added");
                                bundlesToAdd.add(bundle);
                                if (existingBundle != null) {
                                    Trace.debug(FirmwareManifestSync.TAG, "Out of date bundle will be deleted");
                                    bundlesToDelete.add(existingBundle);
                                }
                            } else {
                                Trace.debug(FirmwareManifestSync.TAG, "Firmware has already been downloaded.");
                            }
                        }
                    }
                    ArrayList<ContentProviderOperation> operations = new ArrayList();
                    FirmwareBundleManager firmwareFileManager = FirmwareManifestSync.this.getFileManager();
                    List<String> ids = new ArrayList();
                    for (FirmwareManifestBundle bundle2 : bundlesToDelete) {
                        ids.add(String.valueOf(bundle2.getId()));
                    }
                    if (!ids.isEmpty()) {
                        operations.add(PblFirmwareManifestModel.getDeleteOp(ids));
                    }
                    for (FirmwareManifestBundle bundle22 : bundlesToAdd) {
                        firmwareFileManager.downloadFile(bundle22.getNormalMetadata().getUrl());
                        operations.add(PblFirmwareManifestModel.getInsertOp(bundle22.getContentValues()));
                    }
                    try {
                        if (!operations.isEmpty()) {
                            FirmwareManifestSync.this.getContext().getContentResolver().applyBatch("com.getpebble.android.internal.provider", operations);
                        }
                    } catch (RemoteException e) {
                        Trace.error(FirmwareManifestSync.TAG, "Failed to update firmware manifests.", e);
                    } catch (OperationApplicationException e2) {
                        Trace.error(FirmwareManifestSync.TAG, "Failed to update firmware manifests.", e2);
                    } catch (SQLiteException e3) {
                        Trace.error(FirmwareManifestSync.TAG, "Failed to update firmware manifests.", e3);
                    }
                    for (FirmwareManifestBundle bundle222 : bundlesToDelete) {
                        firmwareFileManager.deleteFile(bundle222.getNormalMetadata().getUrl());
                    }
                    Trace.debug(FirmwareManifestSync.TAG, "Updating firmware manifests complete!");
                    return true;
                }

                public void onTaskSuccess() {
                }

                public void onTaskFailed() {
                }
            }.submit();
        }
    }

    public String fetchLatestFirmwareUriForDevice(PblDevice device) {
        ReleaseType releaseType = getUpdateChannel();
        if (releaseType.equals(ReleaseType.UNKNOWN)) {
            Trace.error(TAG, "Unknown release type: Cannot fetch firmware bundle.");
            return null;
        }
        HardwarePlatform hardwarePlatform = fetchHardwarePlatformForDevice(device);
        if (hardwarePlatform.equals(HardwarePlatform.UNKNOWN)) {
            Trace.error(TAG, "Unknown hardware platform: Cannot fetch firmware bundle.");
            return null;
        }
        FirmwareManifestBundle firmwareManifestBundle = findMatchingBundle(hardwarePlatform, releaseType, fetchCurrentManifests());
        if (firmwareManifestBundle == null) {
            Trace.debug(TAG, "Downloading latest FirmwareManifestBundle");
            firmwareManifestBundle = fetchBundle(hardwarePlatform, releaseType);
        }
        return firmwareManifestBundle.getNormalMetadata().getUrl();
    }

    protected FirmwareBundleManager getFileManager() {
        return new FirmwareBundleManager(getContext());
    }

    protected FirmwareManifestBundle fetchBundle(HardwarePlatform hardwarePlatform, ReleaseType releaseType) {
        FirmwareManifestBundle bundle = new FirmwareManifestFetcher(getContext(), hardwarePlatform, releaseType).fetch();
        if (bundle != null && bundle.getNormalMetadata() != null && bundle.getReleaseType() != null && bundle.getHardwarePlatform() != null) {
            return bundle;
        }
        Trace.warning(TAG, "Got no bundle or invalid bundle with missing data.");
        return null;
    }

    ReleaseType getUpdateChannel() {
        Context context = getContext();
        ReleaseType releaseType = ReleaseType.UNKNOWN;
        if (context == null) {
            return releaseType;
        }
        return ReleaseType.fromString(new PblPreferences(context).getStringData(PrefKey.RELEASE_CHANNEL, ReleaseType.RELEASE_V2.getPath()));
    }

    private HardwarePlatform fetchHardwarePlatformForDevice(PblDevice device) {
        return PblDeviceModel.getPblDeviceRecord(getContext().getContentResolver(), device).hwPlatform;
    }

    protected Map<HardwarePlatform, FirmwareVersion> fetchPlatformVersionData() {
        Map<HardwarePlatform, FirmwareVersion> platformVersionData = new HashMap();
        String[] projection = new String[]{"hw_platform", "fw_version", "fw_timestamp"};
        Cursor cursor = getContext().getContentResolver().query(PblContentProviderUtil.getTableUri("devices"), projection, "last_connected_time is not NULL", null, null);
        if (cursor != null) {
            while (cursor.moveToNext()) {
                HardwarePlatform hardwarePlatform = HardwarePlatform.fromInt(UnsignedInteger.fromIntBits(cursor.getInt(cursor.getColumnIndex("hw_platform"))));
                Trace.debug(TAG, "Hardware platform: " + hardwarePlatform.toString());
                if (!hardwarePlatform.equals(HardwarePlatform.UNKNOWN)) {
                    FirmwareVersion oldestFirmwareVersion = null;
                    if (platformVersionData.containsKey(hardwarePlatform)) {
                        oldestFirmwareVersion = (FirmwareVersion) platformVersionData.get(hardwarePlatform);
                    }
                    String firmwareTag = cursor.getString(cursor.getColumnIndex("fw_version"));
                    long firmwareTimestamp = cursor.getLong(cursor.getColumnIndex("fw_timestamp"));
                    Trace.debug(TAG, "Firmware version: " + firmwareTag);
                    FirmwareVersion firmwareVersion = new FirmwareVersion(firmwareTag, firmwareTimestamp);
                    if (oldestFirmwareVersion == null || firmwareVersion.compareTo(oldestFirmwareVersion) < 0) {
                        platformVersionData.put(hardwarePlatform, firmwareVersion);
                    }
                }
            }
            cursor.close();
        }
        return platformVersionData;
    }

    private List<FirmwareManifestBundle> fetchCurrentManifests() {
        Cursor cursor = PblFirmwareManifestModel.getFirmwareManifests(getContext().getContentResolver(), null);
        List<FirmwareManifestBundle> bundles = new ArrayList();
        if (cursor != null) {
            while (cursor.moveToNext()) {
                ContentValues contentValues = new ContentValues();
                DatabaseUtils.cursorRowToContentValues(cursor, contentValues);
                bundles.add(FirmwareManifestBundle.fromContentValues(contentValues));
            }
            cursor.close();
        }
        return bundles;
    }

    private static FirmwareManifestBundle findMatchingBundle(HardwarePlatform hardwarePlatform, ReleaseType releaseType, List<FirmwareManifestBundle> bundles) {
        for (FirmwareManifestBundle bundle : bundles) {
            if (bundle.getHardwarePlatform().equals(hardwarePlatform) && bundle.getReleaseType().equals(releaseType)) {
                return bundle;
            }
        }
        return null;
    }
}
